package com.hengxinguotong.zhihuichengjian.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.TaskAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.Task;
import com.hengxinguotong.zhihuichengjian.bean.TaskListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.SubmitTaskActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.TaskListActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/7/14.
 */

public class TaskFragment extends BaseFragment {
    private View rootView = null;
    private TaskListActivity mActivity;

    @BindView(R.id.task_lv)
    PullToRefreshListView taskLv;
    @BindView(R.id.et_project)
    HXTextView etProject;

    private TaskAdapter taskAdapter;
    private int pageIndex = 1;
    private List<Task> tasks;
    private int state = 1;
    private String pfId = null;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    List<Task> mDatas = (List<Task>) msg.obj;
                    addData(mDatas);
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_task_list, null);
            ButterKnife.bind(this, rootView);
            mActivity = (TaskListActivity) getActivity();
            state = getArguments().getInt("state");
            taskLv.setMode(PullToRefreshBase.Mode.BOTH);
            tasks = new ArrayList<>();
            taskAdapter = new TaskAdapter(mActivity, tasks);
            taskLv.setAdapter(taskAdapter);
            setListener();
        }else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    Runnable MyRunnable = new Runnable() {
        @Override
        public void run() {
            taskLv.setRefreshing();
        }
    };

    public static TaskFragment newInstance(int state){
        Bundle bundle = new Bundle();
        bundle.putInt("state",state);
        TaskFragment fragment = new TaskFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    private void setListener(){
        taskLv.setMode(PullToRefreshBase.Mode.BOTH);
        taskLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mActivity, SubmitTaskActivity.class);
                intent.putExtra("task", tasks.get(position - 1));
                startActivityForResult(intent, 1);
            }
        });

        taskLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getcTaskInfo(null);
//                mActivity.getTaskCount();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getcTaskInfo(null);
            }
        });
    }

    public void reLoad(){
        if(taskLv != null){
            handler.postDelayed(MyRunnable, 500);
        }
    }

    @OnClick({R.id.search_ll, R.id.iv_p, R.id.state_select_tv, R.id.et_project})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_ll:
            case R.id.iv_p:
            case R.id.state_select_tv:
            case R.id.et_project:
                Intent intent = new Intent(mActivity, PersonLiableListActivity.class);
                intent.putExtra("type", 0);
                startActivityForResult(intent, 2);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == TaskListActivity.UPDATE) {
            reLoad();
            mActivity.getTaskCount();
        }
        if(data != null){
            if(requestCode == 2 && resultCode == 1){
                User user = (User) data.getSerializableExtra("selectUser");
                pfId = user.getUserId();
                etProject.setText(user.getName());
                reLoad();
            }
        }
    }

    private void getcTaskInfo(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            if (!hasList()) {
                jsonObject.put("userId", SPUtil.getString(mActivity, "userId"));
            }
            if(null != pfId){
                jsonObject.put("pfId", pfId);
            }
            jsonObject.put("pageNum", pageIndex);
            jsonObject.put("constructionId", SPUtil.getString(mActivity, "constructionid"));
            jsonObject.put("status", state + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, mActivity, "/taskDistribution/queryList/" + SPUtil.getString(mActivity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (taskLv.isRefreshing()) {
                    taskLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    TaskListRes taskListRes = gson.fromJson(json, TaskListRes.class);
                    Message msg = handler.obtainMessage();
                    msg.what = 1;
                    msg.obj = taskListRes.getValue();
                    msg.sendToTarget();
                }
            }

            @Override
            public void onFailure(String json) {
                if (taskLv.isRefreshing()) {
                    taskLv.onRefreshComplete();
                }
            }
        });
    }

    private void addData(List<Task> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(taskLv);
            }else{
                dismissEmptyView();
            }
            tasks = datas;
            if (datas.size() == Utils.ONCECOUNT) {
                taskLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            tasks.addAll(datas);
        }
        taskAdapter.setDatas(tasks);
        if (datas.size() < Utils.ONCECOUNT) {
            taskLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    @Override
    public void onLazyLoad() {
        handler.postDelayed(MyRunnable, 500);

    }
}
